#include <mc920.h>
#include <stdio.h>
#include "image.h"

#define DEBUG

#define _F_CALC(F, U, X, M) F(2*M_PI*U*X/M)
#define F_REAL(U, X, M) _F_CALC(cos, U, X, M)
#define F_IMG(U, X, M) _F_CALC(sin, U, X, M)

DGrayImage* slow_fourrier(GrayImage *img)
{
   DGrayImage* dimg;
   Vector *vec;
   double val;
   int i, j, u, v;

   dimg = CreateDGrayImage(img->nx, img->ny);

   for (u = 0; u < img->nx; u++)
   {
#ifdef DEBUG
      printf("FTransform on %d:", u);
#endif
      for (v = 0; v < img->ny; v++)
      {
#ifdef DEBUG
         putchar('.');         
         fflush(stdout);
#endif
         for (i = 0; i < img->nx; i++)
         {
            for (j = 0; j < img->ny; j++)
            {
               val = (double)img->val[j][i];

               vec = &(dimg->val[v][u]);
               vec->real = F_REAL(u, i, img->nx) * val;
               vec->img =  F_IMG(v, j, img->ny)  * val;
            }
         }
      }

#ifdef DEBUG
      putchar('\n');
#endif
   }

   return dimg;
}

int main(int argn, char** argv)
{
   GrayImage* img;
   GrayImage* fimg;
   DGrayImage *dimg;
   char* output_path;

   if (argn < 2)
   {
      printf("Usage:\n%s image.pgm\n", argv[0]);
      exit(1);
   }

   img = ReadGrayImage(argv[1]);

   if (img == NULL)
   {
      printf("Error reading image %s\n", argv[1]);
      exit(1);
   }

   output_path = "result.pgm";

   dimg = slow_fourrier(img);

   fimg = ConvertToGrayImage(dimg);

   TransposeGrayImage(fimg);

   WriteGrayImage(fimg, output_path);

   DestroyDGrayImage(dimg);
   DestroyGrayImage(&img);
   DestroyGrayImage(&fimg);

   return 0;
}
